//
//  ProblemContainerViewController.m
//  Utils
//
//  Created by enghou on 2018/4/17.
//  Copyright © 2018年 xyxorigation. All rights reserved.
//

#import "ProblemContainerViewController.h"
#import "ProblemHandleViewController.h"
#import "ProblemUpViewController.h"
#import "ProblemBackViewController.h"
#import "ProblemDoneHandleViewController.h"
#import "ProblemFetchViewController.h"
#import "NetWorkerManager.h"
#import "FileItemModel.h"
@interface ProblemContainerViewController ()

@property(nonatomic,strong)UIPageViewController *page;

@property(nonatomic,strong)NSMutableArray *ctlArray;

@property(nonatomic,copy)NSString *typeId;

@property(nonatomic,strong)NSMutableArray *images;

@property(nonatomic,strong)NSMutableArray *videos;

@property(nonatomic,strong)NSMutableArray *audios;

@end

@implementation ProblemContainerViewController

-(NSString *)typeId{
    ProblemHandleViewController *p = [self.page viewControllers][0];
    return p.typeId;
}

-(NSMutableArray *)images{
    ProblemHandleViewController *p = [self.page viewControllers][0];
    return p.images;
}

-(NSMutableArray *)videos{
    ProblemHandleViewController *p = [self.page viewControllers][0];
    return p.videos;
}

-(NSMutableArray *)audios{
    ProblemHandleViewController *p = [self.page viewControllers][0];
    return p.audios;
}

-(NSDictionary *)param{
    ProblemHandleViewController *p = [self.page viewControllers][0];
    return [p param];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    
    self.title = @"矛盾纠纷办理";
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithTitle:@"确定" style:UIBarButtonItemStylePlain target:self action:@selector(doneAction)];
    self.navigationItem.rightBarButtonItem.tintColor = [UIColor whiteColor];
    self.page = [[UIPageViewController alloc]initWithTransitionStyle:UIPageViewControllerTransitionStyleScroll navigationOrientation:UIPageViewControllerNavigationOrientationHorizontal options:nil];
    for(id subview in _page.view.subviews){
        if([subview isKindOfClass:UIScrollView.class]){
            [subview performSelector:@selector(setScrollEnabled:) withObject:@0];
            break;
        }
    }
    self.page.view.frame = self.view.bounds;
    [self.view addSubview:self.page.view];
    
    ProblemHandleViewController *handle = (ProblemHandleViewController *)[VCLoader vcWithName:@"ProblemHandleViewController"];
    handle.type = self.type;
    handle.typeId = @"10";
    ProblemHandleViewController *handle1;
    if (self.type == 0) {
        handle1 = (ProblemHandleViewController *)[VCLoader vcWithName:@"ProblemDoneHandleViewController"];
        handle1.typeId = @"10";
    }else{
        handle1 = (ProblemHandleViewController *)[VCLoader vcWithName:@"HandleDoneViewController"];
        handle1.typeId = @"30";
    }
    handle1.type = self.type;
    ProblemHandleViewController *handle2 = (ProblemHandleViewController *)[VCLoader vcWithName:@"ProblemFetchViewController"];
    handle2.type = self.type;
    ProblemHandleViewController *handle3 = (ProblemHandleViewController *)[VCLoader vcWithName:@"ProblemUpViewController"];
    handle3.type = self.type;
    ProblemHandleViewController *handle4 = (ProblemHandleViewController *)[VCLoader vcWithName:@"ProblemBackViewController"];
    handle4.type = self.type;
    handle.eventId = self.eventId;
    handle.theDelete = self;
    handle.stepId = self.stepId;
    handle.actions = self.operations;
    handle1.eventId = self.eventId;
    handle1.stepId = self.stepId;
    handle1.actions = self.operations;
    handle1.theDelete = self;
    handle2.eventId = self.eventId;
    handle2.stepId = self.stepId;
    handle2.actions = self.operations;
    handle2.theDelete = self;
    handle3.eventId = self.eventId;
    handle3.actions = self.operations;
    handle3.stepId = self.stepId;
    handle3.theDelete = self;
    handle4.eventId = self.eventId;
    handle4.actions = self.operations;
    handle4.stepId = self.stepId;
    handle4.theDelete = self;
    
    NSArray *ctls = @[handle,handle1,handle2,handle3,handle4];
    self.ctlArray = [ctls mutableCopy];
    [self.page setViewControllers:@[self.ctlArray[0]] direction:UIPageViewControllerNavigationDirectionForward animated:NO completion:nil];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(changeVCWithNot:) name:@"ChangeNot" object:nil];
}

-(void)changeVCWithNot:(NSNotification *)not{
    NSString *code = not.object;
    for (ProblemHandleViewController *vc in self.ctlArray) {
        if ([vc.typeId isEqualToString:code]) {
            [self.page setViewControllers:@[vc] direction:UIPageViewControllerNavigationDirectionForward animated:NO completion:nil];
        }
    }
}

-(void)doEventWithFiles:(NSArray *)files{
    [self beginLoading];
    if (self.type == 0) {
        NSMutableDictionary *param = [[self param]mutableCopy];
        NSMutableArray *filePaths = [NSMutableArray array];
        for (FileItemModel *model in files) {
            [filePaths addObject:model.path];
        }
        param[@"filePaths"] = [filePaths componentsJoinedByString:@","];
        [[NetWorkerManager sharedInstance]handleProblemWithCode:self.typeId param:param successBlock:^(BaseModel *model) {
            [self endLoading];
            if (model.success) {
                [(BaseViewController *)self.parentViewController pop];
            }else{
                [self alertSome:model.msg];
            }
        } failBlock:^(NSInteger code) {
            [self endLoading];
            [self alertSome:kNetWorkFail];
        }];
    }else if (self.type == 1){
        if ([self.typeId isEqualToString:@"70"]){
            //交办
            NSMutableDictionary *param = [[self param]mutableCopy];
            NSMutableArray *filePaths = [NSMutableArray array];
            for (FileItemModel *model in files) {
                [filePaths addObject:model.path];
            }
            param[@"filePaths"] = [filePaths componentsJoinedByString:@","];
            [[NetWorkerManager sharedInstance]postWithPath:@"/mobile/comprehensiveGovernance/appeal/processingAppealByProcessCode.action" parameter:param completeBlock:^(NSDictionary *source) {
                BaseModel *model = [[BaseModel alloc]initWithSourceDict:source];
                [self endLoading];
                if (model.success) {
                    [(BaseViewController *)self.parentViewController pop];
                }else{
                    [self alertSome:model.msg];
                }
            } failBlock:^(NSInteger code) {
                [self endLoading];
                [self alertSome:kNetWorkFail];
            }];
        }else{
            NSMutableDictionary *param = [[self param]mutableCopy];
            NSMutableArray *filePaths = [NSMutableArray array];
            for (FileItemModel *model in files) {
                [filePaths addObject:model.path];
            }
            param[@"filePaths"] = [filePaths componentsJoinedByString:@","];
            [[NetWorkerManager sharedInstance]postWithPath:@"/mobile/comprehensiveGovernance/appeal/processingAppealByProcessCode.action" parameter:param completeBlock:^(NSDictionary *source) {
                BaseModel *model = [[BaseModel alloc]initWithSourceDict:source];
                [self endLoading];
                if (model.success) {
                    [(BaseViewController *)self.parentViewController pop];
                }else{
                    [self alertSome:model.msg];
                }
            } failBlock:^(NSInteger code) {
                [self endLoading];
                [self alertSome:kNetWorkFail];
            }];
        }
    }
}

-(void)doneAction{
    //先要上传
    NSDictionary *param = [self param];
    if (param) {
        [self uploadFilesSuccessBlock:^(NSArray *files){
            //上传参数
            [self doEventWithFiles:files];
        }];
    }
}

-(void)uploadFilesSuccessBlock:(void(^)(NSArray *))complete{
    __block NSInteger maxTask = 0;
    __block NSInteger taskCompleteCount = 0;
    NSMutableArray *files = [NSMutableArray array];
    NSMutableArray *ims = [NSMutableArray array];
    [self.images enumerateObjectsUsingBlock:^(UIImage *obj, NSUInteger idx, BOOL * _Nonnull stop) {
        if (obj.size.width > 0) {
            if (idx == 0) {
                maxTask++;
            }
            NSData *data = UIImageJPEGRepresentation(obj, 0.1);
            [ims addObject:data];
        }
    }];
    NSMutableArray *videos = [NSMutableArray array];
    [self.videos enumerateObjectsUsingBlock:^(NSURL *obj, NSUInteger idx, BOOL * _Nonnull stop) {
        if ([obj.absoluteString length] > 0) {
            NSData *data = [NSData dataWithContentsOfFile:obj.path];
            if (data) {
                if (idx == 0) {
                    maxTask++;
                }
                [videos addObject:data];
            }
        }
    }];
    NSMutableArray *audios = [NSMutableArray array];
    [self.audios enumerateObjectsUsingBlock:^(NSURL *obj, NSUInteger idx, BOOL * _Nonnull stop) {
        if ([obj.absoluteString length] > 0) {
            NSData *data = [NSData dataWithContentsOfFile:obj.path];
            if (data) {
                if (idx == 0) {
                    maxTask++;
                }
                [audios addObject:data];
            }
        }
    }];
    if ([videos count] > 0) {
        NSLog(@"videos = %@",videos);
        [self beginLoading];
        [[NetWorkerManager sharedInstance]uploadVideoWithPath:kUploadFilePath parameter:nil files:videos fileName:@"file" suffix:@"mp4" completeBlock:^(NSDictionary *source) {
            [self endLoading];
            BaseModel *model = [[BaseModel alloc]initWithSourceDict:source listItemClass:NSClassFromString(@"FileItemModel")];
            if (model.success) {
                taskCompleteCount++;
                [files addObjectsFromArray:model.list];
                if (taskCompleteCount == maxTask) {
                    complete(files);
                }
            }
        } failBlock:^(NSInteger code) {
            [self endLoading];
        }];
    }
    if ([audios count] > 0) {
        NSLog(@"audios = %@",audios);
        [[NetWorkerManager sharedInstance]uploadVideoWithPath:kUploadFilePath parameter:nil files:videos fileName:@"file" suffix:@"mp4" completeBlock:^(NSDictionary *source) {
            [self endLoading];
            BaseModel *model = [[BaseModel alloc]initWithSourceDict:source listItemClass:NSClassFromString(@"FileItemModel")];
            if (model.success) {
                taskCompleteCount++;
                [files addObjectsFromArray:model.list];
                if (taskCompleteCount == maxTask) {
                    complete(files);
                }
            }
        } failBlock:^(NSInteger code) {
            [self endLoading];
        }];
    }
    if ([ims count] > 0) {
        NSLog(@"images = %@",ims);
        [self beginLoading];
        [[NetWorkerManager sharedInstance]uploadImageWithPath:kUploadFilePath parameter:nil files:ims fileName:@"file" suffix:@"jpg" completeBlock:^(NSDictionary *source) {
            [self endLoading];
            BaseModel *model = [[BaseModel alloc]initWithSourceDict:source listItemClass:NSClassFromString(@"FileItemModel")];
            if (model.success) {
                taskCompleteCount++;
                [files addObjectsFromArray:model.list];
                if (taskCompleteCount == maxTask) {
                    complete(files);
                }
            }
        } failBlock:^(NSInteger code) {
            [self endLoading];
        }];
    }
    if (maxTask == 0) {
        complete(@[]);
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
